package com.dpwgc.consumer.utils;

import com.dpwgc.consumer.model.Dn;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * RocketMQ工具类
 */
@Component
public class RocketMQUtil {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 向消息队列发送信息
     */
    public boolean pushMessage(Dn dn){

        boolean[] flag = {false};

        //异步发送消息
        rocketMQTemplate.asyncSend("broker-a", MessageBuilder.withPayload(dn).build(),new SendCallback(){
            @Override
            public void onSuccess(SendResult sendResult) {
                flag[0] = true;
            }
            @Override
            public void onException(Throwable e) {
                flag[0] = false;
            }
        });
        return flag[0];
    }

    /**
     * 消费信息
     */
    /*
    @Slf4j
    @Component
    @RocketMQMessageListener(topic = "broker-a", consumerGroup = "19jsj6b-group")
    public static class PopMessage implements RocketMQListener<Log>, RocketMQPushConsumerLifecycleListener {

        @Autowired
        LogMapper logMapper;

        //从消息队列中取出消息
        @Override
        public void onMessage(Log log) {
            try{
                Log log1 = logMapper.checkUploadLog(log.getStuId(),log.getProjectId());
                if(log1==null){
                    logMapper.insertUploadLog(log);
                }
                else {
                    log1.setUrl(log.getUrl());
                    log1.setUploadTime(log.getUploadTime());
                    logMapper.updateUploadLog(log1);
                }
            }catch(Exception e){
                //抛出异常后，MQClient会返回ConsumeConcurrentlyStatus.RECONSUME_LATER,这条消息会再次尝试消费
                System.err.println("消息确认失败："+e);
                throw new RuntimeException(e);
            }
        }
        @Override
        public void prepareStart(DefaultMQPushConsumer consumer) {
            //拉取间隔，单位:毫秒
            consumer.setPullInterval(2000);
            //每次拉取的消息数
            consumer.setPullBatchSize(4);
        }
    }
     */
}
